package com.wfit.service.impl;


import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.toolkit.BeanUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wfit.context.UserContext;
import com.wfit.dto.CartDto;
import com.wfit.mapper.CartMapper;
import com.wfit.po.Cart;
import com.wfit.po.Commodity;
import com.wfit.result.Result;
import com.wfit.service.CartService;
import com.wfit.service.CommodityService;
import com.wfit.vo.CartVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;


@Service
public class CartServiceImpl extends ServiceImpl<CartMapper, Cart> implements CartService {
    @Autowired
    private CommodityService commodityService;

    @Override
    public Result addCart(CartDto dto) {
        Commodity byId = commodityService.getById(dto.getCid());
        // 跟新库存
        if (byId.getNumber() - dto.getNumber() < 0) {
            return Result.error("库存不足");
        }
        if (dto.getCid() == null) return Result.error("数据不能为空");

        Cart one = lambdaQuery().eq(Cart::getCid, dto.getCid()).one();
        // 减少库存
        byId.setNumber(byId.getNumber() - dto.getNumber());
        commodityService.updateById(byId);
        if (one == null) {

            // 生成购物车 新增
            Cart cart = new Cart();
            cart.setNumber(dto.getNumber());
            cart.setAmount(byId.getPrice() * dto.getNumber());
            cart.setName(byId.getName());
            cart.setImage(byId.getImage());
            cart.setCreateTime(LocalDateTime.now());
            cart.setUid(UserContext.getUser());
            cart.setCid(dto.getCid().toString());
            save(cart);

        }
        if (one != null) {
            // 更新
            if (dto.getNumber() == null) dto.setNumber(1);
            one.setNumber(dto.getNumber());
            updateById(one);
        }

        Integer count = lambdaQuery().eq(Cart::getUid, UserContext.getUser()).count();
        return Result.success(count);
    }

    @Override
    public Result getlist() {
        Long user = UserContext.getUser();
        List<Cart> list = lambdaQuery().eq(Cart::getUid, user).list();


            List<CartVO> cartVOS1 = BeanUtil.copyToList(list, CartVO.class);
        for (CartVO cartVO : cartVOS1) {
            cartVO.setIsChecked(true);
        }

        return Result.success(cartVOS1);
    }

    @Override
    public Result delectCart(String cartIds) {
        if (cartIds == null) {
            return Result.error("数据不能为空");
        }
        String[] split = cartIds.split(",");
        for (String string : split) {
            boolean b = removeById(string);
        }
        return Result.success();
    }
}



